
#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //设置根节点的名字
    ui->treeWidget->setHeaderLabel("动物");


    //新增底层节点
    QTreeWidgetItem* item1 = new QTreeWidgetItem();
    item1->setText(0,"猫");//每个节点可以设置多列
    //添加到顶层节点中
   ui->treeWidget->addTopLevelItem(item1);



   QTreeWidgetItem* item2 = new QTreeWidgetItem();
   item2->setText(0,"狗");//每个节点可以设置多列
   //添加到顶层节点中
  ui->treeWidget->addTopLevelItem(item2);

  QTreeWidgetItem* item3 = new QTreeWidgetItem();
  item3->setText(0,"鸟");//每个节点可以设置多列
  //添加到顶层节点中
 ui->treeWidget->addTopLevelItem(item3);

    //添加节点
 QTreeWidgetItem * item4 = new  QTreeWidgetItem();
 item4->setText(0,"中华田园猫");
 item1->addChild(item4);//添加子节点

 QTreeWidgetItem * item5 = new  QTreeWidgetItem();
 item5->setText(0,"布偶猫");
 item1->addChild(item4);


 QTreeWidgetItem * item6 = new  QTreeWidgetItem();
 item6->setText(0,"暹罗");
 item1->addChild(item6);
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_inserttop_clicked()
{
    //先获取到输入框里的内容
    const QString&text= ui->lineEdit->text();
    QTreeWidgetItem*item= new QTreeWidgetItem();
    item->setText(0,text);

    //添加到顶层节点中
    ui->treeWidget->addTopLevelItem(item);
}

void Widget::on_pushButton_insertitem_clicked()
{
    //获取到当前选中的节点
    QTreeWidgetItem * currentItem= ui->treeWidget->currentItem();//获取到当前选中的节点, 返回 QTreeWidgetItem*
    if(currentItem == nullptr)
    {
        return  ;
    }
    //先获取到输入框里的内容
    const QString&text= ui->lineEdit->text();
     //构造一个QTreeWidgetItem
    QTreeWidgetItem*item= new QTreeWidgetItem();
    item->setText(0,text);

    //插入到选中节点的子节点
    currentItem->addChild(item);
}

void Widget::on_pushButton_delete_clicked()
{
    //先获取到选中的元素
    QTreeWidgetItem* currentItem= ui->treeWidget->currentItem();
    if(currentItem==nullptr)//判空
    {
        return ;
    }
    //删除选中的元素，需要先获取到父元素，通过父元素进行删除
    QTreeWidgetItem* parent =  currentItem->parent();
    if(parent==nullptr)
    {

        //顶层元素
        int index = ui->treeWidget->indexOfTopLevelItem(currentItem);//获取前节点第几个
        ui->treeWidget->takeTopLevelItem(index);
    }else{
        //普通元素
        parent->removeChild(currentItem);
    }
}
